package com.sc.nft.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sc.nft.dao.DigitalCollectionDao;
import com.sc.nft.dao.UserCollectionDao;
import com.sc.nft.entity.DigitalCollection;
import com.sc.nft.entity.UserCollection;
import com.sc.nft.service.UserCollectionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class GenerateCollectionNumberTask {
    private final UserCollectionService userCollectionService;
    private final UserCollectionDao userCollectionDao;
    private final DigitalCollectionDao digitalCollectionDao;
    @XxlJob("generateCollectionNumber")
    public void generateCollectionNumber() throws Exception {
        List<UserCollection> list = userCollectionDao.getNoNumbering();
        Map<Long,List<UserCollection>> collectionMaps = Maps.newHashMap();
        for (UserCollection userCollection : list) {
            List<UserCollection> userCollections = collectionMaps.get(userCollection.getCollectionId());
            if(CollUtil.isEmpty(userCollections)){
                userCollections = Lists.newArrayList();
                collectionMaps.put(userCollection.getCollectionId(),userCollections);
            }
            userCollections.add(userCollection);
        }
        for (Map.Entry<Long, List<UserCollection>> entry : collectionMaps.entrySet()) {
            Long collectionId = entry.getKey();
            List<UserCollection> collections = entry.getValue();
            // 获取全部的已售的订单编号
            List<UserCollection> byCollectionId = userCollectionDao.getByCollectionId(collectionId);
            // 获取指定的藏品数据
            DigitalCollection byId = digitalCollectionDao.getById(collectionId);
            // 总数量
            Integer sumCount = byId.getSumCount();
            // 存储总库存数
            List<Integer> allSumCountNumber = new ArrayList<>();
            // 库存编号有1-总数进行初始化
            for (int i = 1; i < sumCount + 1; i++) {
                allSumCountNumber.add(i);
            }
            // 把所有已售的订单编号进行汇总,获取该商品总数,把总数加载到集合中,排除汇总订单编号,把长度进行随机,让后进行get获取,即为新的编号
            List<Integer> collect = byCollectionId.stream().map(UserCollection::getNumbering).collect(Collectors.toList());
            // 获取差集
            allSumCountNumber.removeAll(collect);
            List<Integer> numbers = RandomUtil.randomEleList(allSumCountNumber, collections.size());
            for (int i = 0; i < collections.size(); i++) {
                userCollectionDao.updateNumbering(collections.get(i).getId(),numbers.get(i));
            }

        }
    }


}
